/*
    * Copyright (c) 2024 Hunan OpenValley Digital Industry Development Co., Ltd.
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *     http://www.apache.org/licenses/LICENSE-2.0
    *
    * Unless required by applicable law or agreed to in writing, software
    * distributed under the License is distributed on an "AS IS" BASIS,
    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    * See the License for the specific language governing permissions and
    * limitations under the License.
 */

#include "file_share_callback_stub.h"
#include "jsonUtil.hpp"

namespace OHOS {
namespace FileShare {
FileShareCallbackStub::FileShareCallbackStub()
{
    LOGD("[FileShareCallbackStub::FileShareCallbackStub] start.");

    baseFuncs_[ON_SEND_EVENT] = &FileShareCallbackStub::OnSendEventStub;
    baseFuncs_[ON_SHARE_STATUS_EVENT] = &FileShareCallbackStub::OnShareStatusEventStub;
}

FileShareCallbackStub::~FileShareCallbackStub()
{
    LOGD("[FileShareCallbackStub::~FileShareCallbackStub] start.");

    baseFuncs_.clear();
}

int32_t FileShareCallbackStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel &reply, MessageOption &option)
{
    LOGD("OnRemoteRequest start, cmd: %{public}u", code);
    auto itFunc = baseFuncs_.find(code);
    if (itFunc != baseFuncs_.end()) {
        auto memberFunc = itFunc->second;
        if (memberFunc != nullptr)
        {
            return (this->*memberFunc)(data, reply);
        }
    }
    LOGD("remoterequest no member function default process");
    return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}

int32_t FileShareCallbackStub::OnSendEventStub(MessageParcel &data, MessageParcel &reply)
{
    LOGD("OnSendEventStub start.");

    SendState state = (SendState) data.ReadInt32();

    std::string infoStr = data.ReadString();
    nlohmann::json jsonObject = nlohmann::json::parse(infoStr);
    if (jsonObject.is_discarded()) {
        LOGE("OnSendEventStub parse error");
        return FS_INVALID_PARAM;
    }
    SendInfo info;
    JsonToSendInfo(jsonObject, info);
    
    int32_t ret = OnSendEvent(state, info);
    if (ret != FS_SUCCESS) {
        LOGE("OnSendEvent failed, ret: %{public}d", ret);
        return ret;
    }

    return FS_SUCCESS; 
}

int32_t FileShareCallbackStub::OnShareStatusEventStub(MessageParcel &data, MessageParcel &reply)
{
    LOGD("SendFileStub start.");

    bool shareStatus = data.ReadBool();

    int32_t ret = OnShareStatusEvent(shareStatus);
    if (ret != FS_SUCCESS) {
        LOGE("OnShareStatusEvent failed, ret: %{public}d", ret);
        return ret;
    }

    return FS_SUCCESS; 
}
} // namespace FileShare
} // namespace OHOS